from __future__ import annotations

from fastapi import HTTPException, Request
from fastapi.exceptions import RequestValidationError, ResponseValidationError
from fastapi.responses import JSONResponse

from app.api.response import success_response


async def http_exception_handler(_: Request, exc: HTTPException):
  # Normalize FastAPI HTTPException to unified shape
  detail = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
  # Use HTTP status code as error code by default
  return JSONResponse(status_code=exc.status_code, content=success_response(None, code=exc.status_code, message=detail))


async def validation_exception_handler(_: Request, exc: RequestValidationError):
  # Collapse validation error messages
  messages = []
  try:
    for err in exc.errors():
      loc = ".".join(map(str, err.get("loc", [])))
      msg = err.get("msg", "Invalid")
      messages.append(f"{loc}: {msg}" if loc else msg)
  except Exception:  # pragma: no cover
    messages.append("Validation failed")
  message = "; ".join(messages) if messages else "Validation failed"
  return JSONResponse(status_code=422, content=success_response(None, code=422, message=message))


async def generic_exception_handler(_: Request, exc: Exception):
  # Avoid leaking internals; log could be added later
  return JSONResponse(status_code=500, content=success_response(None, code=500, message=str(exc) or "Internal Server Error"))


async def response_validation_exception_handler(_: Request, exc: ResponseValidationError):
  # Serialize response model mismatch to unified shape, mark as 500 to引导尽快修复
  return JSONResponse(status_code=500, content=success_response(None, code=500, message="Response schema validation failed"))
